package com.changgou.user.controller;
import com.changgou.entity.PageResult;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.user.config.TokenDecode;
import com.changgou.user.service.ProvincesService;
import com.changgou.user.service.UserService;
import com.changgou.user.pojo.User;
import com.changgou.util.SMSUtils;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private TokenDecode tokenDecode;

    @Autowired
    private UserService userService;

    @Autowired
    private ProvincesService provincesService;

    /**
     * 查询全部数据
     * @return
     */
    @GetMapping
    public Result findAll(){
        List<User> userList = userService.findAll();
        return new Result(true, StatusCode.OK,"查询成功",userList) ;
    }

    /***
     * 根据ID查询数据
     * @param username
     * @return
     */
    @GetMapping("/{username}")
    public Result findById(@PathVariable String username){
        User user = userService.findById(username);
        return new Result(true,StatusCode.OK,"查询成功",user);
    }
    @GetMapping("/load/{username}")
    public User findUserInfo(@PathVariable("username") String username){
        User user = userService.findById(username);
        System.out.println(user.getPassword());
        return user;
    }

    /***
     * 新增数据
     * @param user
     * @return
     */
    @PostMapping
    public Result add(@RequestBody User user){
        userService.add(user);
        return new Result(true,StatusCode.OK,"添加成功");
    }


    /***
     * 修改数据
     * @param user
     * @param username
     * @return
     */
    @PutMapping(value="/{username}")
    public Result update(@RequestBody User user,@PathVariable String username){
        user.setUsername(username);
        userService.update(user);
        return new Result(true,StatusCode.OK,"修改成功");
    }


    /***
     * 根据ID删除品牌数据
     * @param username
     * @return
     */
    @DeleteMapping(value = "/{username}" )
    public Result delete(@PathVariable String username){
        userService.delete(username);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    /***
     * 多条件搜索品牌数据
     * @param searchMap
     * @return
     */
    @GetMapping(value = "/search" )
    public Result findList(@RequestParam Map searchMap){
        List<User> list = userService.findList(searchMap);
        return new Result(true,StatusCode.OK,"查询成功",list);
    }


    /***
     * 分页搜索实现
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}" )
    public Result findPage(@RequestParam Map searchMap, @PathVariable  int page, @PathVariable  int size){
        Page<User> pageList = userService.findPage(searchMap, page, size);
        PageResult pageResult=new PageResult(pageList.getTotal(),pageList.getResult());
        return new Result(true,StatusCode.OK,"查询成功",pageResult);
    }

    /**
     * 修改密码
     * @param password
     * @return
     */
    @PutMapping("/updatePassword/{password}")
    public Result updatePassword(@PathVariable("password") String password){
        User user = new User();
        String username = tokenDecode.getUserInfo().get("username");
        user.setUsername(username);

        String gensalt = BCrypt.gensalt();
        String saltPassword = BCrypt.hashpw(password, gensalt);
        user.setPassword(saltPassword);
        userService.update(user);
        return new Result(true,StatusCode.OK,"修改成功");
    }

    @GetMapping("/findAllArea")
    public Result findAllArea() {
        List<Map<String, Object>> provinceList = provincesService.findAllArea();
        return new Result(true,StatusCode.OK,"查询成功", provinceList);
    }

    @GetMapping("/sendCode")
    public Result sendCode(HttpSession session) {
        String username = tokenDecode.getUserInfo().get("username");
        User user = userService.findById(username);
        String phone = user.getPhone();
        try{
            String random=(int)((Math.random()*9+1)*100000)+"";
            System.out.println("创建的验证码为："+random);
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,phone,random);
            session.setAttribute(username, random);
            session.setMaxInactiveInterval(3 * 60);
            Object attribute = session.getAttribute(username);
            return new Result(true, StatusCode.OK,"成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"操作失败");
        }
    }

    @GetMapping("/checkCode")
    public Result checkCode(String code, HttpSession session) {
        String username = tokenDecode.getUserInfo().get("username");
        String checkCode = (String) session.getAttribute(username);
        if (code.equals(checkCode)) {
            return new Result(true, StatusCode.OK,"正确");
        } else {
            return new Result(false, StatusCode.ERROR, "错误");
        }
    }

    /**
     * 修改手机号
     * @param phone
     * @return
     */
    @PutMapping("/changePhone/{phone}")
    public Result changePhone(@PathVariable("phone") String phone){
        User user = new User();
        String username = tokenDecode.getUserInfo().get("username");
        user.setUsername(username);
        user.setPhone(phone);
        userService.update(user);
        return new Result(true,StatusCode.OK,"查询成功");
    }

}
